"""
接口自动化相关API路由
"""

import logging
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, func

from ...core.database import get_db
from ...core.security import get_current_user
from ...models.user import User
from ...models.api_automation import (
    ApiInterface, ApiParameter, ApiAssertion, TestScenario, FlowNode, FlowConnection,
    ScenarioExecution, StepExecutionResult, EnvironmentConfig
)
from ...schemas.api_automation import (
    ApiInterface as ApiInterfaceSchema,
    ApiInterfaceCreate, ApiInterfaceUpdate, ApiInterfaceListParams, ApiInterfaceListResponse,
    TestScenario as TestScenarioSchema,
    TestScenarioCreate, TestScenarioUpdate, TestScenarioListParams, TestScenarioListResponse,
    ScenarioExecution as ScenarioExecutionSchema,
    ScenarioExecutionListParams, ScenarioExecutionListResponse,
    EnvironmentConfig as EnvironmentConfigSchema,
    EnvironmentConfigCreate, EnvironmentConfigUpdate,
    ApiTestRequest, ApiTestResponse,
    ScenarioExecuteRequest, ScenarioExecuteResponse, ScenarioDebugRequest,
    ApiParameterCreate, ApiParameterUpdate, ApiParameter as ApiParameterSchema,
    ApiAssertionCreate, ApiAssertionUpdate, ApiAssertion as ApiAssertionSchema,
    FlowNode as FlowNodeSchema, FlowNodeCreate, FlowNodeUpdate,
    FlowConnection as FlowConnectionSchema, FlowConnectionCreate, FlowConnectionUpdate,
    FlowConnectionResponse, ScenarioFlowData, ScenarioFlowResponse
)
from ...services.api_automation_service import api_automation_service
from ...services.flow_execution_service import flow_execution_engine

router = APIRouter()
logger = logging.getLogger(__name__)


# ==================== API接口管理 ====================

@router.get("/interfaces", response_model=ApiInterfaceListResponse)
async def list_interfaces(
    params: ApiInterfaceListParams = Depends(),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取接口列表"""
    query = db.query(ApiInterface)
    
    # 搜索过滤
    if params.search:
        query = query.filter(
            or_(
                ApiInterface.name.contains(params.search),
                ApiInterface.description.contains(params.search),
                ApiInterface.url.contains(params.search)
            )
        )
    
    # 分类过滤
    if params.category:
        query = query.filter(ApiInterface.category == params.category)
    
    # 状态过滤
    if params.status:
        query = query.filter(ApiInterface.status == params.status)
    
    # 方法过滤
    if params.method:
        query = query.filter(ApiInterface.method == params.method)
    
    # 计算总数
    total = query.count()
    
    # 分页
    interfaces = query.offset((params.page - 1) * params.size).limit(params.size).all()
    
    return ApiInterfaceListResponse(
        items=interfaces,
        total=total,
        page=params.page,
        size=params.size,
        pages=(total + params.size - 1) // params.size
    )


@router.post("/interfaces", response_model=ApiInterfaceSchema)
async def create_interface(
    interface_data: ApiInterfaceCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建接口"""
    try:
        # 创建接口
        interface = ApiInterface(
            **interface_data.dict(exclude={"parameters", "assertions"}),
            created_by=current_user.id
        )
        db.add(interface)
        db.flush()  # 获取ID
        
        # 创建参数
        for param_data in interface_data.parameters or []:
            parameter = ApiParameter(**param_data.dict(), interface_id=interface.id, created_by=current_user.id)
            db.add(parameter)
        
        # 创建断言
        for assertion_data in interface_data.assertions or []:
            assertion = ApiAssertion(**assertion_data.dict(), interface_id=interface.id, created_by=current_user.id)
            db.add(assertion)
        
        db.commit()
        db.refresh(interface)
        
        return interface
        
    except Exception as e:
        logger.error(f"创建接口失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建接口失败")


@router.get("/interfaces/{interface_id}", response_model=ApiInterfaceSchema)
async def get_interface(
    interface_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取接口详情"""
    interface = db.query(ApiInterface).filter(ApiInterface.id == interface_id).first()
    if not interface:
        raise HTTPException(status_code=404, detail="接口不存在")
    
    return interface


@router.put("/interfaces/{interface_id}", response_model=ApiInterfaceSchema)
async def update_interface(
    interface_id: int,
    interface_data: ApiInterfaceUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新接口"""
    interface = db.query(ApiInterface).filter(ApiInterface.id == interface_id).first()
    if not interface:
        raise HTTPException(status_code=404, detail="接口不存在")
    
    try:
        # 更新接口基本信息
        for field, value in interface_data.dict(exclude_unset=True).items():
            setattr(interface, field, value)
        
        db.commit()
        db.refresh(interface)
        
        return interface
        
    except Exception as e:
        logger.error(f"更新接口失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新接口失败")


@router.delete("/interfaces/{interface_id}")
async def delete_interface(
    interface_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除接口"""
    interface = db.query(ApiInterface).filter(ApiInterface.id == interface_id).first()
    if not interface:
        raise HTTPException(status_code=404, detail="接口不存在")
    
    try:
        db.delete(interface)
        db.commit()
        
        return {"message": "接口删除成功"}
        
    except Exception as e:
        logger.error(f"删除接口失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除接口失败")


# ==================== 接口参数管理 ====================

@router.post("/interfaces/{interface_id}/parameters", response_model=ApiParameterSchema)
async def create_parameter(
    interface_id: int,
    parameter_data: ApiParameterCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建接口参数"""
    interface = db.query(ApiInterface).filter(ApiInterface.id == interface_id).first()
    if not interface:
        raise HTTPException(status_code=404, detail="接口不存在")
    
    try:
        parameter = ApiParameter(**parameter_data.dict(), interface_id=interface_id, created_by=current_user.id)
        db.add(parameter)
        db.commit()
        db.refresh(parameter)
        
        return parameter
        
    except Exception as e:
        logger.error(f"创建参数失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建参数失败")


@router.put("/parameters/{parameter_id}", response_model=ApiParameterSchema)
async def update_parameter(
    parameter_id: int,
    parameter_data: ApiParameterUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新接口参数"""
    parameter = db.query(ApiParameter).filter(ApiParameter.id == parameter_id).first()
    if not parameter:
        raise HTTPException(status_code=404, detail="参数不存在")
    
    try:
        for field, value in parameter_data.dict(exclude_unset=True).items():
            setattr(parameter, field, value)
        
        db.commit()
        db.refresh(parameter)
        
        return parameter
        
    except Exception as e:
        logger.error(f"更新参数失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新参数失败")


@router.delete("/parameters/{parameter_id}")
async def delete_parameter(
    parameter_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除接口参数"""
    parameter = db.query(ApiParameter).filter(ApiParameter.id == parameter_id).first()
    if not parameter:
        raise HTTPException(status_code=404, detail="参数不存在")
    
    try:
        db.delete(parameter)
        db.commit()
        
        return {"message": "参数删除成功"}
        
    except Exception as e:
        logger.error(f"删除参数失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除参数失败")


# ==================== 接口断言管理 ====================

@router.post("/interfaces/{interface_id}/assertions", response_model=ApiAssertionSchema)
async def create_assertion(
    interface_id: int,
    assertion_data: ApiAssertionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建接口断言"""
    interface = db.query(ApiInterface).filter(ApiInterface.id == interface_id).first()
    if not interface:
        raise HTTPException(status_code=404, detail="接口不存在")
    
    try:
        assertion = ApiAssertion(**assertion_data.dict(), interface_id=interface_id, created_by=current_user.id)
        db.add(assertion)
        db.commit()
        db.refresh(assertion)
        
        return assertion
        
    except Exception as e:
        logger.error(f"创建断言失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建断言失败")


@router.put("/assertions/{assertion_id}", response_model=ApiAssertionSchema)
async def update_assertion(
    assertion_id: int,
    assertion_data: ApiAssertionUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新接口断言"""
    assertion = db.query(ApiAssertion).filter(ApiAssertion.id == assertion_id).first()
    if not assertion:
        raise HTTPException(status_code=404, detail="断言不存在")
    
    try:
        for field, value in assertion_data.dict(exclude_unset=True).items():
            setattr(assertion, field, value)
        
        db.commit()
        db.refresh(assertion)
        
        return assertion
        
    except Exception as e:
        logger.error(f"更新断言失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新断言失败")


@router.delete("/assertions/{assertion_id}")
async def delete_assertion(
    assertion_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除接口断言"""
    assertion = db.query(ApiAssertion).filter(ApiAssertion.id == assertion_id).first()
    if not assertion:
        raise HTTPException(status_code=404, detail="断言不存在")
    
    try:
        db.delete(assertion)
        db.commit()
        
        return {"message": "断言删除成功"}
        
    except Exception as e:
        logger.error(f"删除断言失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除断言失败")


# ==================== 接口测试 ====================

@router.post("/interfaces/test", response_model=ApiTestResponse)
async def test_interface(
    test_request: ApiTestRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """测试接口"""
    try:
        result = await api_automation_service.test_api_interface(test_request, db)
        return result
        
    except Exception as e:
        logger.error(f"接口测试失败: {str(e)}")
        raise HTTPException(status_code=500, detail="接口测试失败")


# ==================== 测试场景管理 ====================

@router.get("/scenarios", response_model=TestScenarioListResponse)
async def list_scenarios(
    params: TestScenarioListParams = Depends(),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场景列表"""
    query = db.query(TestScenario)
    
    # 搜索过滤
    if params.search:
        query = query.filter(
            or_(
                TestScenario.name.contains(params.search),
                TestScenario.description.contains(params.search)
            )
        )
    
    # 状态过滤
    if params.status:
        query = query.filter(TestScenario.status == params.status)
    
    # 创建者过滤
    if params.created_by:
        query = query.filter(TestScenario.created_by == params.created_by)
    
    # 计算总数
    total = query.count()
    
    # 分页
    scenarios = query.offset((params.page - 1) * params.size).limit(params.size).all()
    
    return TestScenarioListResponse(
        items=scenarios,
        total=total,
        page=params.page,
        size=params.size,
        pages=(total + params.size - 1) // params.size
    )


@router.post("/scenarios", response_model=TestScenarioSchema)
async def create_scenario(
    scenario_data: TestScenarioCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建测试场景"""
    try:
        # 创建场景
        scenario = TestScenario(
            **scenario_data.dict(exclude={"steps"}),
            created_by=current_user.id
        )
        db.add(scenario)
        db.flush()  # 获取ID
        
        # 步骤创建已废弃，使用流程图替代
        # 旧的步骤系统已被流程图系统替代
        
        db.commit()
        db.refresh(scenario)
        
        return scenario
        
    except Exception as e:
        logger.error(f"创建场景失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建场景失败")


@router.get("/scenarios/{scenario_id}", response_model=TestScenarioSchema)
async def get_scenario(
    scenario_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场景详情"""
    scenario = db.query(TestScenario).filter(TestScenario.id == scenario_id).first()
    if not scenario:
        raise HTTPException(status_code=404, detail="场景不存在")
    
    return scenario


@router.put("/scenarios/{scenario_id}", response_model=TestScenarioSchema)
async def update_scenario(
    scenario_id: int,
    scenario_data: TestScenarioUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新测试场景"""
    scenario = db.query(TestScenario).filter(TestScenario.id == scenario_id).first()
    if not scenario:
        raise HTTPException(status_code=404, detail="场景不存在")
    
    try:
        # 更新场景基本信息
        update_data = scenario_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(scenario, field, value)
        
        # 步骤更新已废弃，使用流程图替代
        # 旧的步骤系统已被流程图系统替代
        
        db.commit()
        db.refresh(scenario)
        
        return scenario
        
    except Exception as e:
        logger.error(f"更新场景失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新场景失败")


@router.delete("/scenarios/{scenario_id}")
async def delete_scenario(
    scenario_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除测试场景"""
    scenario = db.query(TestScenario).filter(TestScenario.id == scenario_id).first()
    if not scenario:
        raise HTTPException(status_code=404, detail="场景不存在")
    
    try:
        db.delete(scenario)
        db.commit()
        
        return {"message": "场景删除成功"}
        
    except Exception as e:
        logger.error(f"删除场景失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除场景失败")


# ==================== 场景步骤管理 ====================

# 旧的步骤API端点已废弃，使用流程图API替代
# @router.post("/scenarios/{scenario_id}/steps", response_model=ScenarioStepSchema)
# @router.put("/steps/{step_id}", response_model=ScenarioStepSchema)  
# @router.delete("/steps/{step_id}")
# 这些端点已被流程图API替代


# ==================== 场景执行 ====================

@router.post("/scenarios/execute", response_model=ScenarioExecuteResponse)
async def execute_scenario(
    execute_request: ScenarioExecuteRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """执行测试场景"""
    try:
        result = await api_automation_service.execute_scenario(execute_request, db, current_user.id)
        return result
        
    except Exception as e:
        logger.error(f"场景执行失败: {str(e)}")
        raise HTTPException(status_code=500, detail="场景执行失败")


@router.post("/scenarios/debug", response_model=ScenarioExecuteResponse)
async def debug_scenario(
    debug_request: ScenarioDebugRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """调试测试场景"""
    try:
        # 转换为执行请求
        execute_request = ScenarioExecuteRequest(
            scenario_id=debug_request.scenario_id,
            environment_id=debug_request.environment_id,
            variables=debug_request.variables,
            debug_mode=True
        )
        
        result = await api_automation_service.execute_scenario(execute_request, db, current_user.id)
        return result
        
    except Exception as e:
        logger.error(f"场景调试失败: {str(e)}")
        raise HTTPException(status_code=500, detail="场景调试失败")


# ==================== 执行记录管理 ====================

@router.get("/executions", response_model=ScenarioExecutionListResponse)
async def list_executions(
    params: ScenarioExecutionListParams = Depends(),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取执行记录列表"""
    query = db.query(ScenarioExecution)
    
    # 场景过滤
    if params.scenario_id:
        query = query.filter(ScenarioExecution.scenario_id == params.scenario_id)
    
    # 状态过滤
    if params.status:
        query = query.filter(ScenarioExecution.status == params.status)
    
    # 执行者过滤
    if params.executor_id:
        query = query.filter(ScenarioExecution.executor_id == params.executor_id)
    
    # 时间范围过滤
    if params.start_date:
        query = query.filter(ScenarioExecution.created_at >= params.start_date)
    if params.end_date:
        query = query.filter(ScenarioExecution.created_at <= params.end_date)
    
    # 计算总数
    total = query.count()
    
    # 分页和排序
    executions = query.order_by(ScenarioExecution.created_at.desc()).offset(
        (params.page - 1) * params.size
    ).limit(params.size).all()
    
    return ScenarioExecutionListResponse(
        items=executions,
        total=total,
        page=params.page,
        size=params.size,
        pages=(total + params.size - 1) // params.size
    )


@router.get("/executions/{execution_id}", response_model=ScenarioExecutionSchema)
async def get_execution(
    execution_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取执行记录详情"""
    execution = db.query(ScenarioExecution).filter(ScenarioExecution.id == execution_id).first()
    if not execution:
        raise HTTPException(status_code=404, detail="执行记录不存在")
    
    return execution


# ==================== 环境配置管理 ====================

@router.get("/environments", response_model=List[EnvironmentConfigSchema])
async def list_environments(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取环境配置列表"""
    environments = db.query(EnvironmentConfig).filter(EnvironmentConfig.is_active == True).all()
    return environments


@router.post("/environments", response_model=EnvironmentConfigSchema)
async def create_environment(
    env_data: EnvironmentConfigCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建环境配置"""
    try:
        # 如果设置为默认环境，先取消其他默认环境
        if env_data.is_default:
            db.query(EnvironmentConfig).filter(EnvironmentConfig.is_default == True).update(
                {"is_default": False}
            )
        
        environment = EnvironmentConfig(**env_data.dict(), created_by=current_user.id)
        db.add(environment)
        db.commit()
        db.refresh(environment)
        
        return environment
        
    except Exception as e:
        logger.error(f"创建环境配置失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建环境配置失败")


@router.put("/environments/{env_id}", response_model=EnvironmentConfigSchema)
async def update_environment(
    env_id: int,
    env_data: EnvironmentConfigUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新环境配置"""
    environment = db.query(EnvironmentConfig).filter(EnvironmentConfig.id == env_id).first()
    if not environment:
        raise HTTPException(status_code=404, detail="环境配置不存在")
    
    try:
        # 如果设置为默认环境，先取消其他默认环境
        if env_data.is_default:
            db.query(EnvironmentConfig).filter(
                and_(EnvironmentConfig.is_default == True, EnvironmentConfig.id != env_id)
            ).update({"is_default": False})
        
        for field, value in env_data.dict(exclude_unset=True).items():
            setattr(environment, field, value)
        
        db.commit()
        db.refresh(environment)
        
        return environment
        
    except Exception as e:
        logger.error(f"更新环境配置失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新环境配置失败")


@router.delete("/environments/{env_id}")
async def delete_environment(
    env_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除环境配置"""
    environment = db.query(EnvironmentConfig).filter(EnvironmentConfig.id == env_id).first()
    if not environment:
        raise HTTPException(status_code=404, detail="环境配置不存在")
    
    try:
        db.delete(environment)
        db.commit()
        
        return {"message": "环境配置删除成功"}
        
    except Exception as e:
        logger.error(f"删除环境配置失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除环境配置失败")


# ==================== 流程图管理 ====================

@router.get("/scenarios/{scenario_id}/flow", response_model=ScenarioFlowResponse)
async def get_scenario_flow(
    scenario_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取场景流程图"""
    scenario = db.query(TestScenario).filter(TestScenario.id == scenario_id).first()
    if not scenario:
        raise HTTPException(status_code=404, detail="场景不存在")
    
    # 获取流程节点
    nodes = db.query(FlowNode).filter(FlowNode.scenario_id == scenario_id).all()
    
    # 获取流程连接
    connections = db.query(FlowConnection).filter(FlowConnection.scenario_id == scenario_id).all()
    
    # 创建数据库ID到前端ID的映射
    db_id_to_node_id = {node.id: node.node_id for node in nodes}
    
    # 转换连接数据，将数据库ID映射回前端字符串ID
    transformed_connections = []
    for conn in connections:
        source_node_id = db_id_to_node_id.get(conn.source_node_id)
        target_node_id = db_id_to_node_id.get(conn.target_node_id)
        
        if source_node_id and target_node_id:
            # 创建连接响应对象，使用前端的字符串ID
            transformed_conn = FlowConnectionResponse(
                id=conn.id,
                connection_id=conn.connection_id,
                name=conn.name,
                source_node_id=source_node_id,  # 使用前端字符串ID
                target_node_id=target_node_id,  # 使用前端字符串ID
                condition_config=conn.condition_config,
                connection_type=conn.connection_type,
                is_enabled=conn.is_enabled,
                scenario_id=conn.scenario_id,
                created_at=conn.created_at,
                updated_at=conn.updated_at
            )
            transformed_connections.append(transformed_conn)
    
    return ScenarioFlowResponse(
        nodes=nodes,
        connections=transformed_connections
    )


@router.post("/scenarios/{scenario_id}/flow")
async def save_scenario_flow(
    scenario_id: int,
    flow_data: ScenarioFlowData,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """保存场景流程图"""
    scenario = db.query(TestScenario).filter(TestScenario.id == scenario_id).first()
    if not scenario:
        raise HTTPException(status_code=404, detail="场景不存在")
    
    try:
        # 删除现有的流程图数据
        db.query(FlowConnection).filter(FlowConnection.scenario_id == scenario_id).delete()
        db.query(FlowNode).filter(FlowNode.scenario_id == scenario_id).delete()
        
        # 创建节点映射表（前端ID -> 数据库ID）
        node_id_mapping = {}
        
        # 创建新的流程节点
        for node_data in flow_data.nodes:
            node_dict = node_data.dict()
            node = FlowNode(
                scenario_id=scenario_id,
                created_by=current_user.id,
                **node_dict
            )
            db.add(node)
            db.flush()  # 获取生成的ID
            node_id_mapping[node_data.node_id] = node.id
        
        # 创建新的流程连接
        for connection_data in flow_data.connections:
            connection_dict = connection_data.dict()
            
            # 查找源节点和目标节点的数据库ID
            source_db_id = None
            target_db_id = None
            
            for node_data in flow_data.nodes:
                if node_data.node_id == connection_data.source_node_id:
                    source_db_id = node_id_mapping[node_data.node_id]
                if node_data.node_id == connection_data.target_node_id:
                    target_db_id = node_id_mapping[node_data.node_id]
            
            if source_db_id and target_db_id:
                connection = FlowConnection(
                    scenario_id=scenario_id,
                    connection_id=connection_data.connection_id,
                    name=connection_data.name,
                    source_node_id=source_db_id,
                    target_node_id=target_db_id,
                    condition_config=connection_data.condition_config,
                    connection_type=connection_data.connection_type,
                    created_by=current_user.id,
                    is_enabled=connection_data.is_enabled
                )
                db.add(connection)
        
        db.commit()
        
        return {"message": "流程图保存成功"}
        
    except Exception as e:
        logger.error(f"保存流程图失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="保存流程图失败")


@router.put("/scenarios/{scenario_id}/flow/nodes/{node_id}", response_model=FlowNodeSchema)
async def update_flow_node(
    scenario_id: int,
    node_id: int,
    node_data: FlowNodeUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新流程节点"""
    node = db.query(FlowNode).filter(
        and_(FlowNode.id == node_id, FlowNode.scenario_id == scenario_id)
    ).first()
    
    if not node:
        raise HTTPException(status_code=404, detail="节点不存在")
    
    try:
        # 更新节点数据
        update_data = node_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(node, field, value)
        
        db.commit()
        db.refresh(node)
        
        return node
        
    except Exception as e:
        logger.error(f"更新节点失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新节点失败")


@router.delete("/scenarios/{scenario_id}/flow/nodes/{node_id}")
async def delete_flow_node(
    scenario_id: int,
    node_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除流程节点"""
    node = db.query(FlowNode).filter(
        and_(FlowNode.id == node_id, FlowNode.scenario_id == scenario_id)
    ).first()
    
    if not node:
        raise HTTPException(status_code=404, detail="节点不存在")
    
    try:
        # 删除相关连接
        db.query(FlowConnection).filter(
            or_(
                FlowConnection.source_node_id == node_id,
                FlowConnection.target_node_id == node_id
            )
        ).delete()
        
        # 删除节点
        db.delete(node)
        db.commit()
        
        return {"message": "节点删除成功"}
        
    except Exception as e:
        logger.error(f"删除节点失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除节点失败")


@router.post("/scenarios/{scenario_id}/execute-flow", response_model=ScenarioExecuteResponse)
async def execute_scenario_flow(
    scenario_id: int,
    request: ScenarioExecuteRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """执行基于流程图的测试场景"""
    # 确保请求中的场景ID与路径参数一致
    request.scenario_id = scenario_id
    
    # 调用流程图执行引擎
    result = await flow_execution_engine.execute_scenario_flow(request, db, current_user.id)
    
    return result


@router.post("/scenarios/{scenario_id}/debug-flow", response_model=ScenarioExecuteResponse)
async def debug_scenario_flow(
    scenario_id: int,
    request: ScenarioDebugRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """调试基于流程图的测试场景"""
    # 转换为执行请求
    execute_request = ScenarioExecuteRequest(
        scenario_id=scenario_id,
        environment_id=request.environment_id,
        variables=request.variables,
        debug_mode=True
    )
    
    # 调用流程图执行引擎
    result = await flow_execution_engine.execute_scenario_flow(execute_request, db, current_user.id)
    
    return result